<template>
  <div>
    <!-- 需求计划提报(N+1) -->
    <TopFilter :list="topFilterList" ref="top" :cols="3" @filterChange="changeTopHandle" @onCollapse="collapseHandle" :labelWidth="110"></TopFilter>

    <Spin :spinning="exportLoading" tip="Loading...">
      <FilterTable
        ref="table"
        columnsRef="wkcMonthPlanReport"
        :isSelectColumn="false"
        :columns="columns"
        :fetchapi="fetchApi"
        :params="fetchParams"
        :datakey="'records'"
        :onColumnsChange="(columns) => (this.columns = columns)"
      >
        <template slot="controls">
          <el-button size="small" type="text" style="font-size: 14px; font-weight: bold; margin-right: 20px">
            <!--            <span v-text="`本月：${showData.currMonth}`"></span>-->
            <!--            <span v-text="`提交状态: ${showData.checkStatus ? '已提交' : '未提交'}`"></span>-->
            <span v-text="`月度计划提报时间为: ${showData.beginDate}至${showData.endDate}`"></span>
          </el-button>
          <el-button size="small" type="primary" @click="lockPlan()">锁定计划</el-button>
          <el-button size="small" type="primary" @click="tranOrder()">计划拆单</el-button>
          <el-button size="small" type="primary" :disabled="isDisabled" @click="addGeneralHandle()">新增常规计划</el-button>
          <el-button size="small" type="primary" :disabled="isDisabled" v-if="false" @click="addHandle(1)">新增追加计划</el-button>
          <!--          <multiuse-button size="small" type="primary" :disabled="isDisabled" :click="oneKeySubmit">一键提交</multiuse-button>-->
          <multiuse-button size="small" type="primary" :click="exportHandle">导 出</multiuse-button>
        </template>
      </FilterTable>
    </Spin>

    <Drawer :visible.sync="isAdd" :title="'新增'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }" width="80%">
      <addModel :isAddPlan="isAddPlan" :isNowMonth="isNowMonth" @close="emitcloseHandler" />
    </Drawer>
    <Drawer :visible.sync="isEmit" :title="'计划信息'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }" width="80%">
      <emitModel :rowData="formData" @close="emitcloseHandler" />
    </Drawer>
    <Drawer :visible.sync="isView" :title="'计划信息'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }" width="80%">
      <viewModel :rowData="formData" @close="viewcloseHandler" />
    </Drawer>
    <BaseDialog :visible.sync="isAddWhatPlan" :title="'订购方式'" destroyOnClose :width="'30%'" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <div>
        <multiuse-button :containerStyle="{ marginLeft: '15%', marginRight: '12%', marginTop: '28px' }" size="big" type="primary" @click="addDiffHandle(1)">追加本月计划</multiuse-button>
        <multiuse-button size="big" type="primary" @click="addDiffHandle(2)">追加次月计划</multiuse-button>
      </div>
      <div
        :style="{
          position: 'absolute',
          left: 0,
          bottom: 0,
          right: 0,
          zIndex: 9,
          borderTop: '1px solid #e9e9e9',
          padding: '10px 20px',
          background: '#fff',
          textAlign: 'right',
        }"
      >
        <el-button @click="addDiffHandle(3)">关 闭</el-button>
      </div>
    </BaseDialog>
  </div>
</template>
<script>
import moment from 'moment';
import { dictionary } from '@/utils/dictMixin';
import { exportExcelFile } from '@/utils';
import { queryList, getDeadlineTime, getStatus, delByIds, exportExcel, updateStatusLock, planTransOrder } from '@/api/dealerSale/salesPlan/MonthPlanReport';
import addModel from './addModel';
import emitModel from './emitModel';
import viewModel from './viewModel';

export default {
  name: 'PlanReportN1',
  mixins: [dictionary],
  data() {
    this.BaseTable = null;
    return {
      topFilterList: this.createdFrom(),
      columns: this.createdTable(),
      fetchApi: queryList,
      fetchParams: { isDealer: 10041001 },
      formData: {},
      showData: {
        currMonth: moment().format('YYYY年MM月'),
        checkStatus: false,
        beginDate: '',
        endDate: '',
      },
      exportLoading: false,
      isDisabled: false,
      isAdd: false,
      isEmit: false,
      isView: false,
      isAddPlan: false,
      isNowMonth: false,
      isAddWhatPlan: false,
    };
  },
  components: {
    addModel,
    emitModel,
    viewModel,
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  created() {
    this.init();
  },
  methods: {
    async lockPlan() {
      this.exportLoading = true;
      const res = await updateStatusLock();
      if (res.resultCode === 200) {
        this.exportLoading = false;
      }
      // 重新加载
      this.fetchParams = { ...this.fetchParams };
    },
    async tranOrder() {
      this.exportLoading = true;
      const res = await planTransOrder();
      if (res.resultCode === 200) {
        this.exportLoading = false;
      }
      // 重新加载
      this.fetchParams = { ...this.fetchParams };
    },
    addDiffHandle(type) {
      if (type === 1) {
        this.isAdd = true;
        this.formData = this.showData;
        this.isAddPlan = true;
        this.isNowMonth = true;
        this.isAddWhatPlan = false;
      } else if (type === 2) {
        this.isAdd = true;
        this.formData = this.showData;
        this.isAddPlan = true;
        this.isNowMonth = false;
        this.isAddWhatPlan = false;
      } else {
        this.isAddWhatPlan = false;
      }
    },
    //添加追加提报
    addHandle(type) {
      this.isAddWhatPlan = true;
    },
    //点击查看事件
    viewHandle(row) {
      this.isView = true;
      this.formData = row;
    },
    //关闭侧边栏事件
    viewcloseHandler(val) {
      this.isView = false;
    },
    //初始化数据
    async init() {
      const res = await getStatus();
      // const res1 = await getDeadlineTime({ reportDate: moment().subtract(-1, 'months').format('YYYY-MM'), setType: 24201001 });
      const res1 = await getDeadlineTime({ reportDate: moment().format('YYYY-MM'), setType: 24201001 });
      if (res.resultCode === 200) {
        this.showData.checkStatus = res.data;
      }
      if (res1.resultCode === 200) {
        if (res1.data !== null) {
          this.showData.beginDate = res1.data.beginDate;
          this.showData.endDate = res1.data.endDate;
        } else {
          this.showData.beginDate = null;
          this.showData.endDate = null;
        }
      }
      this.isDisabled = !res.data;
    },
    //添加常规提报
    addGeneralHandle() {
      if (this.showData.endDate == null || this.showData.beginDate == null) {
        this.$notify.warning({ title: '提示信息', message: '联系管理员配置提报常规计划时间！' });
        return;
      } else if (this.showData.endDate >= moment().format('YYYY-MM-DD') && this.showData.beginDate <= moment().format('YYYY-MM-DD')) {
        this.isAdd = true;
        this.isAddPlan = false;
      } else {
        this.$notify.warning({ title: '提示信息', message: '当前时间不允许提报常规计划！' });
        return;
      }
    },

    //搜索框改变事件
    changeTopHandle(params) {
      this.fetchParams = Object.assign({}, this.fetchParams, params);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    //点击编辑事件
    editHandle(row) {
      this.isEmit = true;
      this.formData = row;
    },
    //关闭侧边栏事件
    emitcloseHandler(val) {
      this.isAdd = false;
      this.isEmit = false;
      // 重新加载
      this.fetchParams = { ...this.fetchParams };
    },

    async delHandle(row) {
      await this.$confirm('是否确认删除', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const res = await delByIds([row.id]);
          if (res.resultCode == 200) {
            this.$notify.success({ title: '提示信息', message: '删除成功' });

            this.fetchParams = { ...this.fetchParams };
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          });
        });
    },
    // // 导出
    async exportHandle() {
      await this.$confirm('是否将Excel表格保存至本地文件夹?', '提示', {
        confirmButtonText: '下载',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.$refs.top.SUBMIT_FORM();
          this.exportLoading = true;
          exportExcel(this.fetchParams)
            .then((response) => {
              exportExcelFile(response.data, 'C端月度计划提报');
              this.exportLoading = false;
            })
            .catch((err) => {
              console.log(err);
            });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消',
          });
        });
    },
    createdFrom() {
      return [
        {
          type: 'INPUT',
          label: '月度计划编号',
          fieldName: 'plan1No',
          placeholder: '请输入',
        },
        {
          type: 'DATE',
          label: '计划年月',
          fieldName: 'planYearAndMonth',
          // initialValue: moment().subtract(-1, 'months').format('YYYY-MM'),
          dateType: 'month',
          // clearable: false,
        },
        {
          type: 'SELECT',
          label: '状态',
          fieldName: 'planStatus',
          placeholder: '请选择',
          itemList: this.createDictList('2404'),
        },
        {
          type: 'SELECT',
          label: '计划类型',
          fieldName: 'plan1Type',
          placeholder: '请选择',
          itemList: this.createDictList('2405'),
        },
      ];
    },
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          fixed: 'left',
          render: (props) => {
            return <span>{props.row.index + 1}</span>;
          },
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <multiuse-button size="mini" type="text" onClick={() => this.editHandle(props.row)} disabled={props.row.planStatus === 24041004}>
                  编辑
                </multiuse-button>
                <el-divider direction="vertical" />
                <multiuse-button size="mini" type="text" onClick={() => this.viewHandle(props.row)}>
                  查看
                </multiuse-button>
                <el-divider direction="vertical" />
                <multiuse-button size="mini" type="text" onClick={() => this.delHandle(props.row)} disabled={props.row.planStatus !== 24041001}>
                  删除
                </multiuse-button>
              </div>
            );
          },
        },
        {
          title: '月度计划编号',
          dataIndex: 'plan1No',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '计划类型',
          dataIndex: 'plan1Type',
          align: 'center',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: (props) => {
            //编码转汉字
            return <span>{this.createDictText(props.row.plan1Type, '2405')}</span>;
          },
        },
        {
          title: '状态',
          dataIndex: 'planStatus',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: (props) => {
            //编码转汉字
            return <span>{this.createDictText(props.row.planStatus, '2404')}</span>;
          },
        },

        {
          title: '计划年月',
          dataIndex: 'planYearAndMonth',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '总提报数量',
          dataIndex: 'planAllNum',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '指标提报数',
          dataIndex: 'planIndexNum',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '配额提报数',
          dataIndex: 'planQuotaNum',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '创建人',
          dataIndex: 'createdBy',
          sorter: true,
          filter: true,
          filterType: 'input',
          // editType: 'select',
          // editItems: [],
        },
        {
          title: '创建时间',
          dataIndex: 'createdAt',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
      ];
    },
  },
};
</script>
